package models

import (
	"fmt"
	"github.com/zw2582/ginlib"
	"time"
)

//Account 账户信息
type Account struct {
	Id int `xorm:"pk autoincr"`
	Name string `xorm:"varchar(32) comment('账号名称')"`
	AppKey string `xorm:"varchar(32) comment('秘钥')"`
	Balance float64 `xorm:"decimal(12,2) comment('账户余额')"`
	ContactUser string `xorm:"varchar(32) comment('联系人')"`
	ContactPhone string `xorm:"varchar(12) comment('联系电话')"`
	ContactEmail string `xorm:"varchar(32) comment('联系人邮箱')"`
	MonthCheck int `xorm:"tinyint(1) comment('1.月结账户 0.非月结账户')"`
	PriceId float64 `xorm:"decimal(12,2) comment('单价*元')"`
	PriceBank2 float64 `xorm:"decimal(12,2) comment('单价*元')"`
	PriceBank3 float64 `xorm:"decimal(12,2) comment('单价*元')"`
	PriceBank4 float64 `xorm:"decimal(12,2) comment('单价*元')"`
	PricePhone2 float64 `xorm:"decimal(12,2) comment('单价*元')"`
	PricePhone3 float64 `xorm:"decimal(12,2) comment('单价*元')"`
	CreatedAt time.Time `xorm:"created"`
	UpdatedAt time.Time `xorm:"updated"`
	Status int `xorm:"tinyint(1) comment('1.有效 0.无效')"`
}

func init()  {
	ginlib.XormAddWaitSync(new(Account))
}

func (this *Account) Save() {
	var err error
	if this.Id == 0 {
		_, err = DB.Insert(this)
	} else {
		_, err = DB.ID(this.Id).Update(this)
	}
	if err != nil {
		panic(err)
	}
}

func AccountGet(accountId int) (obj Account) {
	if accountId == 0{
		return
	}
	DB.Where("id=?", accountId).Get(&obj)
	return
}

//AccountDecr 减少余额
func AccountDecr(accountId int, money float64) error {
	account := AccountGet(accountId)
	if account.Id == 0 {
		return fmt.Errorf("账户不存在")
	}
	if account.MonthCheck == 1 {
		AccountBillMonthAdd(accountId, money)
		return nil
	}
	if account.Balance < money {
		return fmt.Errorf("账户余额不足")
	}

	session := DB.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		panic(err)
	}
	obj := Account{}
	DB.Where("id=?", accountId).ForUpdate().Get(&obj)
	obj.Balance -= money
	if _, err := session.ID(obj.Id).Update(&obj); err != nil {
		panic(err)
	}
	if err := session.Commit(); err != nil {
		panic(err)
	}
	return nil
}